package utils.msg;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;

import model.User;
import model.UserEventDetail;
import thread.JavaSmsApi;
import thread.SmsParameters;

/**
 * 多条件查询与信息发送线程，可以发送短信与邮件
 *
 */
public class ComplexPollingRunnable implements Runnable{
	private UserEventDetail userEventDetail;
	private SmsParameters smsParams;
	private String sender;
	private Date start;//初始为null
	private int gap = 5*60*1000;//5分钟发送一次
	private boolean stop = false;

	public ComplexPollingRunnable(UserEventDetail userEventDetail,
			 String sender,SmsParameters smsParams) {
		this.userEventDetail = userEventDetail;
		this.smsParams = smsParams;
		this.sender = sender;
	}

	public void stopPolling() {
		this.stop = true;
	}

	@Override
	public void run() {
		QueryUtil qu = new QueryUtil();
		while(!stop){
			String msg = qu.generateMsg(sender, userEventDetail);
			if (msg!=null){
				Date now = new Date();
				
				if(start == null || now.getTime()-start.getTime()>=gap){//如果在时间段以内重复发现异常事件不发送，否则发送
					try {
						User user = userEventDetail.getUser();
						String phone = user.getPhoneNumber();
						JavaSmsApi.sendSms(smsParams.getApikey(), msg,phone);
						if(user!=null && user.getEmail()!=null){
							String email = user.getEmail();
							if (email != null && !StringUtils.isBlank(email)){//发送邮件
								System.out.println("JavaMail send ="+JavaMail.sendMail(msg, email));
							}
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
					if(start==null){
						start = now;
					}else{
						start.setTime(now.getTime());
					}
				}
				
			}
			try {
				int interval = userEventDetail.getUserEvent().getPollingTime();
				TimeUnit.MILLISECONDS.sleep(interval);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
